package pushup.popup.actions;

import java.util.Iterator;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import pushup.controller.PushUpController;

public class PushUpAction implements IObjectActionDelegate  {

	private ISelection selection;
	private IWorkbenchPart targetPart = null;
	
	public PushUpAction(){
	
	}

	public void setActivePart(final IAction action, final IWorkbenchPart targetPart) {
		this.targetPart = targetPart;
	}

	public void run(final IAction action) {
		try {
			@SuppressWarnings("unchecked")
			final Iterator<IStructuredSelection> iter = ((IStructuredSelection) selection).iterator();
			while (iter.hasNext()) {
				final IProject currentProject = (IProject) iter.next();
				if (isValidProject(currentProject)) {
					PushUpController.getInstance().subscribeToProject(currentProject);
					break;
				} else {
					showClosedProjectError();
				}
			}
		} catch (final Exception e) {
			System.err.println("Exception in TestAction.run()");
			e.printStackTrace();
		}
	}
	
	private void showClosedProjectError() {
		MessageDialog.openInformation(targetPart.getSite().getShell(),
				"X-Monkey Warning",
				"It is not possible to analyze a closed project");
	}
	
	
	public void selectionChanged(final IAction action, final ISelection selection) {
		this.selection = selection;
		action.setEnabled(!selection.isEmpty());
	}
	
	private boolean isValidProject(final IProject project) {
		return project != null && project.isAccessible();
	}

}
